<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { NDrawer, NForm, NFormItem, NInput, NSelect, NButton, NSpace, useMessage } from 'naive-ui';
import { addDevTask, updateDevTask, type DevTask } from '@/service/api/dataplatform/dev';
import { getDataSourceList } from '@/service/api/dataplatform/datasource';

interface Props {
  visible: boolean;
  operateType: 'add' | 'edit';
  rowData?: DevTask | null;
}

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const message = useMessage();
const loading = ref(false);
const datasourceOptions = ref<Array<{ label: string; value: number }>>([]);

const formModel = ref<DevTask>({
  name: '',
  taskType: 'SQL',
  content: '',
  datasourceId: undefined,
  engineType: 'DORIS',
  scheduleType: 'MANUAL',
  status: 0,
  description: ''
});

const title = computed(() => (props.operateType === 'add' ? '新增任务' : '编辑任务'));

const taskTypeOptions = [
  { label: 'SQL', value: 'SQL' },
  { label: 'Python', value: 'PYTHON' },
  { label: 'Shell', value: 'SHELL' },
  { label: 'Flink', value: 'FLINK' }
];

const engineTypeOptions = [
  { label: 'Doris', value: 'DORIS' },
  { label: 'MySQL', value: 'MYSQL' },
  { label: 'Flink', value: 'FLINK' }
];

const scheduleTypeOptions = [
  { label: '手动执行', value: 'MANUAL' },
  { label: '定时调度', value: 'CRON' },
  { label: '依赖调度', value: 'DEPENDENCY' }
];

// 加载数据源列表
async function loadDataSources() {
  try {
    const res = await getDataSourceList({ pageNum: 1, pageSize: 100 });
    if (res.data) {
      datasourceOptions.value = (res.data.rows || []).map(item => ({
        label: item.name,
        value: item.id!
      }));
    }
  } catch (error) {
    message.error('加载数据源失败');
  }
}

// 监听visible变化
watch(
  () => props.visible,
  val => {
    if (val) {
      loadDataSources();
      if (props.operateType === 'edit' && props.rowData) {
        Object.assign(formModel.value, props.rowData);
      } else {
        resetForm();
      }
    }
  }
);

// 重置表单
function resetForm() {
  Object.assign(formModel.value, {
    name: '',
    taskType: 'SQL',
    content: '',
    datasourceId: undefined,
    engineType: 'DORIS',
    scheduleType: 'MANUAL',
    status: 0,
    description: ''
  });
}

// 关闭抽屉
function handleClose() {
  emit('update:visible', false);
}

// 提交表单
async function handleSubmit() {
  loading.value = true;
  try {
    if (props.operateType === 'add') {
      await addDevTask(formModel.value);
      message.success('创建成功');
    } else {
      await updateDevTask(formModel.value.id!, formModel.value);
      message.success('更新成功');
    }
    emit('success');
  } catch (error) {
    message.error(props.operateType === 'add' ? '创建失败' : '更新失败');
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <NDrawer :show="visible" :width="600" @update:show="handleClose">
    <n-drawer-content :title="title" closable>
      <NForm :model="formModel" label-placement="left" :label-width="100">
        <NFormItem label="任务名称" path="name" required>
          <NInput v-model:value="formModel.name" placeholder="请输入任务名称" />
        </NFormItem>

        <NFormItem label="任务类型" path="taskType" required>
          <NSelect v-model:value="formModel.taskType" :options="taskTypeOptions" />
        </NFormItem>

        <NFormItem label="任务内容" path="content" required>
          <NInput
            v-model:value="formModel.content"
            type="textarea"
            placeholder="请输入SQL或脚本内容"
            :rows="10"
          />
        </NFormItem>

        <NFormItem label="数据源" path="datasourceId">
          <NSelect
            v-model:value="formModel.datasourceId"
            :options="datasourceOptions"
            placeholder="请选择数据源"
            clearable
          />
        </NFormItem>

        <NFormItem label="执行引擎" path="engineType">
          <NSelect v-model:value="formModel.engineType" :options="engineTypeOptions" />
        </NFormItem>

        <NFormItem label="调度类型" path="scheduleType">
          <NSelect v-model:value="formModel.scheduleType" :options="scheduleTypeOptions" />
        </NFormItem>

        <NFormItem label="描述" path="description">
          <NInput
            v-model:value="formModel.description"
            type="textarea"
            placeholder="请输入任务描述"
            :rows="3"
          />
        </NFormItem>
      </NForm>

      <template #footer>
        <NSpace justify="end">
          <NButton @click="handleClose">取消</NButton>
          <NButton type="primary" :loading="loading" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </n-drawer-content>
  </NDrawer>
</template>

<style scoped></style>
